<?php

// 抽奖

namespace app\shop\controller;

use think\Db;
use think\Request;
use think\Controller;
use think\Session;
use app\shop\model\LuckDraw as LuckDrawModel;
use app\shop\model\DrawGoods as DrawGoodsModel;
use app\shop\model\GoodsType as GoodsTypeModel;
use app\shop\model\DrawWinner as DrawWinnerModel;
use app\shop\model\LotteryCode as LotteryCodeModel;


class Draw extends Controller
{

    /**
     * 抽奖中心
     * @param LuckDrawModel $luckDraw
     * @param DrawGoodsModel $drawGoods
     * @param DrawWinnerModel $drawWinner
     * @param LotteryCodeModel $lotteryCode
     * @param GoodsTypeModel $goodsType
     * @return mixed
     */
    // 抽奖主页
    public function index()
    {

        $user_id = Session::get('member_id');
        $giftList = Db::name('sign_info')->where(['status' => 1])->order('id', 'desc')->select()->toArray();
        $restaraunts = array_column($giftList, 'title');
        $cover = array_column($giftList, 'cover');
        $color = array_column($giftList, 'color');
        $data = Db::name('draw_number')->where('id', $user_id)->find();


        return $this->fetch('',[
            'mate_head'   => '抽奖',
            'restaraunts' => json_encode($restaraunts),
            'cover'       => $cover,
            'color'       => json_encode($color),
            'times'       => $data['deal_time'] < date('Y-m-d') ? 3 : $data['number'],
            'total'       => Db::name('sign_log')->group('user_id')->count()
        ]);

    }


    /**
     * 抽奖功能
     * @param string $draw_id
     * @return int
     */
    public function ernie()
    {
        $draw_id = 20;
        $condition['state'] = ['eq', 1];
        $model = new LotteryCodeModel();
        $draw_winner = new DrawWinnerModel();
        $draw_goods = new DrawGoodsModel();
        $draw = (new LuckDrawModel())->where('id', $draw_id)->find();

        $first_prize = $draw['first_prize'];
        $two_prize = $draw['two_prize'];
        $three_prize = $draw['three_prize'];
        $total = $first_prize + $two_prize + $three_prize;

        $all_id = $model->column('id');

        $id_array = array_rand($all_id, $total);

        $first_prize_arr = array_slice($id_array, 0, $first_prize);
        array_splice($id_array, 0, $first_prize);

        $two_prize_id_arr = array_slice($id_array, 0, $two_prize);
        array_splice($id_array, 0, $two_prize);
        $three_prize_id_arr = array_slice($id_array, 0, $three_prize);


        $first_str = "";
        $two_str = "";
        $three_str = "";
        foreach ($first_prize_arr as $value) {
            $first_str .= $all_id[$value] . ',';
        }

        foreach ($two_prize_id_arr as $value) {
            $two_str .= $all_id[$value] . ',';
        }

        foreach ($three_prize_id_arr as $value) {
            $three_str .= $all_id[$value] . ',';
        }

        $first_record = $model->where('id', 'in', $first_str)->field('id,lottery_code,member_id,type_id')->select();
        $two_record = $model->where('id', 'in', $two_str)->field('id,lottery_code,member_id,type_id')->select();
        $three_record = $model->where('id', 'in', $three_str)->field('id,lottery_code,member_id,type_id')->select();

        $first_goods = $draw_goods->where(['draw_id' => $draw_id, 'level' => 1])->find();
        $two_goods = $draw_goods->where(['draw_id' => $draw_id, 'level' => 2])->find();
        $three_goods = $draw_goods->where(['draw_id' => $draw_id, 'level' => 3])->find();

        Db::startTrans();
        try {

            $first_winner = [];
            $delete_str = "";
            foreach ($first_record as $value) {
                $first_winner[] = [
                    'member_id'       => $value['member_id'],
                    'draw_id'         => $draw_id,
                    'goods_id'        => $first_goods['id'],
                    'level'           => 1,
                    'lottery_code'    => $value['lottery_code'],
                    'name'            => '',
                    'phone'           => '',
                    'area_info'       => '',
                    'address'         => '',
                    'picUrl'          => $first_goods['thumb_img'],
                    'tracking_number' => '',
                    'status'          => 1,
                    'create_time'     => date('Y-m-d', time()),
                ];

                if ($value['type_id'] == 2) {
                    $delete_str .= $value['id'] . ',';
                }


            }


            $draw_winner->allowField(true)->saveAll($first_winner);

            $two_winner = [];
            foreach ($two_record as $value) {
                $two_winner[] = [
                    'member_id'       => $value['member_id'],
                    'draw_id'         => $draw_id,
                    'goods_id'        => $two_goods['id'],
                    'level'           => 2,
                    'lottery_code'    => $value['lottery_code'],
                    'name'            => '',
                    'phone'           => '',
                    'area_info'       => '',
                    'address'         => '',
                    'picUrl'          => $first_goods['thumb_img'],
                    'tracking_number' => '',
                    'status'          => 1,
                    'create_time'     => date('Y-m-d', time()),
                ];

                if ($value['type_id'] == 2) {
                    $delete_str .= $value['id'] . ',';
                }
            }

            $draw_winner->allowField(true)->saveAll($two_winner);

            $three_winner = [];
            foreach ($three_record as $value) {
                $three_winner[] = [
                    'member_id'       => $value['member_id'],
                    'draw_id'         => $draw_id,
                    'goods_id'        => $three_goods['id'],
                    'level'           => 3,
                    'lottery_code'    => $value['lottery_code'],
                    'name'            => '',
                    'phone'           => '',
                    'area_info'       => '',
                    'address'         => '',
                    'picUrl'          => $first_goods['thumb_img'],
                    'tracking_number' => '',
                    'status'          => 1,
                    'create_time'     => date('Y-m-d', time()),
                ];

                if ($value['type_id'] == 2) {
                    $delete_str .= $value['id'] . ',';
                }
            }

            $draw_winner->allowField(true)->saveAll($three_winner);

            Db::name('lottery_code')->where('id', 'in', rtrim($delete_str,','))->delete();

            $draw->save(['status' => 1], ['id' => $draw_id]);

            // 提交事务
            Db::commit();
            return 1;

        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();
            return 2;
        }


    }



    public function goods_detail()
    {
        // 获取参数
        $id  = Request::instance()->param('id');

        // 商品信息
        $item = DrawGoodsModel::get($id);


        return $this->fetch('draw_goods_detail',[
           'mate_head' => $item['title'],
            'item'     => $item
        ]);
    }
}